<template>
    <div>
        <div>
            <el-config-provider :locale="zhCn"> <!--《:locale="zhCn 》设置语言-->

                <el-scrollbar height="70vh">
                    <!-- 考勤周期维护 -->
                    <el-row :gutter="24">
                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
                                <el-form-item label="考勤周期维护" label-position="top"
                                    :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                                    <div class="progress-bar">
                                        <div class="progress"></div>
                                    </div>
                                </el-form-item>

                            </div>
                        </el-col>

                        <!--  -->
                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="考勤周期"
                                    label-position="top">
                                    <el-input placeholder="" v-model="formData.attendanceCycle"
                                        style="/*width: 354px;*/" :disabled="!isEditing" />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="考勤周期开始日期"
                                    label-position="top">
                                    <el-date-picker v-model="formData.startDate" style="width: 100%;" type="date"
                                        placeholder="" :size="size" value-format="YYYY-MM-DD" :disabled="!isEditing" />

                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="考勤周期结束日期"
                                    label-position="top">
                                    <el-date-picker v-model="formData.endDate" style="width: 100%;" type="date"
                                        placeholder="" :size="size" value-format="YYYY-MM-DD" :disabled="!isEditing" />

                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="总共天数"
                                    label-position="top">
                                    <el-input placeholder="" v-model="formData.totalDays" style="/*width: 354px;*/"
                                        :disabled="!isEditing" />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="关联查询"
                                    label-position="top">
                                    <!-- <el-scrollbar height="10vh"> -->
                                    <el-table :data="page.records" height="200" stripe>
                                        <el-table-column v-for="col in calendar_columns" :prop="col.id" :key="col.id"
                                            :label="col.label" :width="col.width">
                                            <!-- 对工作状态列单独处理，用 ElTag 渲染 -->
                                            <template #default="scope">
                                                <template v-if="col.id === 'workingCondition'">
                                                    <el-tag effect="dark" :type="getTagType(scope.row[col.id])">
                                                        {{ scope.row[col.id] }}
                                                    </el-tag>
                                                </template>
                                                <template v-else>
                                                    {{ scope.row[col.id] }}
                                                </template>
                                            </template>
                                        </el-table-column>
                                    </el-table>
                                    <!-- </el-scrollbar> -->
                                </el-form-item>

                            </div>
                            <div style="margin: 15px;">
                                <el-pagination @current-change="loadCalendars" v-model:currentPage="page.current"
                                    :page-sizes="[2, 4, 6, 8, 10]" :page-size="page.size" :total="page.total"
                                    layout="total, prev, pager, next">
                                </el-pagination>
                            </div>
                        </el-col>

                        <!--  -->
                        <el-col :span="24">
                            <!-- 空白分隔区域 -->
                            <div style="height: 10px; border-top: 0px dashed #e4e7ed; margin: 6px 0;"></div>
                        </el-col>

                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="工作日数"
                                    label-position="top">
                                    <el-input placeholder="" v-model="formData.workingDays" style="/*width: 354px;*/"
                                        :disabled="!isEditing" />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="休息天数"
                                    label-position="top">
                                    <el-input placeholder="" v-model="formData.restDays" style="/*width: 354px;*/"
                                        :disabled="!isEditing" />
                                </el-form-item>
                            </div>
                        </el-col>

                        <!--  -->
                        <el-col :span="24">
                            <!-- 空白分隔区域 -->
                            <div style="height: 10px; border-top: 0px dashed #e4e7ed; margin: 6px 0;"></div>
                        </el-col>

                        <div class="bottom-submit-bar">
                            <el-button v-if="!isEditing" type="primary" @click="enableEditing">编辑</el-button>
                            <template v-else>
                                <el-button type="primary" @click="submitForm">提交</el-button>
                                <el-button @click="cancelEditing">取消</el-button>
                            </template>
                        </div>

                    </el-row>
                </el-scrollbar>

            </el-config-provider>
        </div>
    </div>
</template>

<script setup>
import { ref, defineEmits, defineProps, watch } from 'vue';
import request from '@/api/request';
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router';

let emits = defineEmits(['ref-table'])
let props = defineProps(['data'])
let formData = ref({
    ...props.data
})

// 监听两个日期字段
watch([() => formData.value.startDate, () => formData.value.endDate], ([newStartDate, newEndDate]) => {
    // 当两个日期都不为空时触发事件
    if (newStartDate && newEndDate) {
        request({
            url: "/workingCalendar/page",
            method: "get",
            params: {
                current: page.value.current,
                size: page.value.size,
                startDate: newStartDate,
                endDate: newEndDate
            }
        }).then(resp => {
            page.value = resp.data
            console.log(page)
        })

        // 计算两个日期之间的天数
        const startDate = new Date(newStartDate);
        const endDate = new Date(newEndDate);

        // 计算时间差（毫秒）
        const timeDifference = endDate.getTime() - startDate.getTime();

        // 转换为天数
        const daysDifference = Math.ceil(timeDifference / (1000 * 60 * 60 * 24)) + 1; // +1包含起始日期

        // 将天数赋值给总共天数字段
        formData.value.totalDays = daysDifference;

        loadCalendars()
    }
})

watch([() => formData.value.totalDays, () => formData.value.workingDays], ([newTotalDays, newWorkingDays]) => {
    if (newTotalDays || newWorkingDays) {
        if (newWorkingDays === null || newWorkingDays === undefined || newWorkingDays === '') {
            newWorkingDays = 0;
        }
        formData.value.restDays = newTotalDays - newWorkingDays;
    }
})

// 添加编辑状态控制变量
const isEditing = ref(false);
// 保存原始数据用于取消编辑时恢复
const originalData = ref({ ...props.data });

// 工作日历表头
const calendar_columns = ref([
    { id: 'dateTime', label: '日期时间', width: '160' },
    { id: 'week', label: '星期', width: '160' },
    { id: 'workingCondition', label: '工作状态', width: '160' },
    { id: 'remark', label: '备注', width: '200' },
    { id: 'festival', label: '节日', width: '200' },
])
// 数据
let page = ref({
    current: 1,
    size: 4,
    total: 0,
    records: []
})

//加载表数据
let loadCalendars = () => {
    request({
        url: "/workingCalendar/page",
        method: "get",
        params: {
            current: page.value.current,
            size: page.value.size,
            startDate: formData.value.startDate,
            endDate: formData.value.endDate
        }
    }).then(resp => {
        page.value = resp.data
    })
}

// 根据状态返回 Tag 类型
const getTagType = (status) => {
    switch (status) {
        case "工作日":
            return "success";
        case "公休日":
            return "primary";
        case "节假日":
            return "warning";
        default:
            return "default";
    }
};

// 启用编辑模式
const enableEditing = () => {
    isEditing.value = true;
};

// 提交表单
const submitForm = () => {
    console.log('提交数据:', formData.value);
    request({
        url: "/attendanceCycle/update",
        method: "post",
        data: formData.value
    }).then(res => {
        // 提交后退出编辑模式
        isEditing.value = false;
        // 通知父组件刷新表格
        emits('ref-table');
        ElMessage.primary(res.msg);
    })
};

// 取消编辑
const cancelEditing = () => {
    // 恢复原始数据
    formData.value = { ...originalData.value };
    isEditing.value = false;
};

loadCalendars()
</script>

<style scoped>
/* 外层容器，可控制整体条的高度、圆角等 */
.progress-bar {
    height: 6px;
    background-color: #ccebf7;
    border-radius: 3px;
    display: flex;
    width: 100%;
    /* 确保进度条容器宽度占满父容器 */
    overflow: hidden;
    /* 防止子元素溢出 */
}

.progress {
    width: 8%;
    height: 10;
    background-color: #61c3ea;
    border-radius: 3px 0 0 3px;
    transition: width 0.3s ease;
    /* 添加宽度变化的过渡效果 */
}

.bottom-submit-bar {
    /* position: fixed; */
    /* 固定定位 */
    bottom: 0;
    /* 靠底部 */
    left: 0;
    width: 100%;
    background-color: #fff;
    /* 背景色，可根据需求调整 */
    border-top: 1px solid #eaeaea;
    /* 顶部边框，与页面区分 */
    padding: 12px 24px;
    /* 内边距，适配截图里的间距风格 */
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    /* 按钮靠左，可根据实际需求调整 */
    z-index: 10;
    /* 提高层级，避免被其他内容覆盖 */
}
</style>
